package com.yeqiangwei.commons.mail;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.yeqiangwei.commons.mail.exception.MailException;
import com.yeqiangwei.commons.util.ValidatorHelper;

public class MailService {

	private static final Logger logger = Logger.getLogger(MailService.class);

	static {

	}

	public static void main(String args[]) {

	}

	public Session getSession(final MailConfig config) {
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", config.getSmtpServer());
		if (config.getSmtpNeedSSL()) { // 判断是否有SSL安全套接字验证
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
			props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.setProperty("mail.smtp.socketFactory.fallback", "false");
		}
		if (!ValidatorHelper.isEmpty(config.getSmtpPort())) {
			props.setProperty("mail.smtp.port", config.getSmtpPort());
			props.setProperty("mail.smtp.socketFactory.port", config.getSmtpPort());
		}
		if (config.getSmtpNeedPassword()) {
			/* SMTP Server需要验证 */
			props.setProperty("mail.smtp.auth", "true");
			return Session.getDefaultInstance(props, new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(config.getSmtpAccount(), config.getSmtpPassword());
				}
			});
		} else {
			props.setProperty("mail.smtp.auth", "false");
			return Session.getDefaultInstance(props);
		}
	}

	/**
	 * 发送单封E-mail
	 * 
	 * @param session
	 * @param entry
	 * @throws MailException
	 */
	public void sendMail(Session session, MailEntity entry) throws MailException {
		if (session == null) {
			throw new MailException("......SMTP Session is null");
		}
		try {
			InternetAddress address;
			try {
				address = new InternetAddress(entry.getFrom(), entry.getSender(), "utf-8");
			} catch (UnsupportedEncodingException e) {
				logger.error(e.toString());
				throw new MailException(e.toString());
			}
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(address);
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(entry.getTo(), false));
			msg.setSubject(entry.getSubject(), "utf-8");// 设置邮件标题
			msg.setSentDate(new Date()); // 邮件发送日期
			if(!ValidatorHelper.isEmpty(entry.getText())){
				msg.setText(entry.getText());// 设置邮件内容
			}
			if(!ValidatorHelper.isEmpty(entry.getHtmlText())){
				//新建一个存放信件内容的BodyPart对象
				BodyPart mdp=new MimeBodyPart();
				//给BodyPart对象设置内容和格式/编码方式
				mdp.setContent(entry.getHtmlText(),"text/html;charset=utf-8");
				//新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)
				Multipart multipart=new MimeMultipart();	
				//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
				multipart.addBodyPart(mdp);
				msg.setContent(multipart);
			}
			if(!ValidatorHelper.isEmpty(entry.getMultipart())){
				msg.setContent(entry.getMultipart());
			}
			Transport.send(msg); // 执行发送
		} catch (MessagingException e) {
			logger.error(e.toString());
			throw new MailException(e.toString());
		} 
	}
}
